﻿/*
 * zunit.cxx
 *
 *  Created on: 2015年4月3日
 *      Author: Fifi Lyu
 */

#include "zpsoe/zalgorithm/zunit.h"
#include "zpsoe/zalgorithm/zdouble.h"
#include "zpsoe/zalgorithm/zint.h"
#include <map>

using std::map;

namespace zpsoe {

namespace zalgorithm {

namespace zunit {

ZPSOE_SHARED_LIB_API string to_str(const unit_type_t sp) {
    static map<unit_type_t, string> sp_map_;
    sp_map_[SIZE_Byte] = "byte";
    sp_map_[SIZE_KiB] = "KiB";
    sp_map_[SIZE_MiB] = "MiB";
    sp_map_[SIZE_GiB] = "GiB";
    sp_map_[SIZE_TiB] = "TiB";
    sp_map_[SIZE_PiB] = "PiB";
    sp_map_[SIZE_KB] = "KB";
    sp_map_[SIZE_MB] = "MB";
    sp_map_[SIZE_GB] = "GB";
    sp_map_[SIZE_TB] = "TB";
    sp_map_[SIZE_PB] = "PB";

    return sp_map_[sp];
}

ZPSOE_SHARED_LIB_API byte_t to_byte(const unit_type_t ut) {
    static map<unit_type_t, byte_t> m_;
    m_[SIZE_Byte] = 1L;
    m_[SIZE_KiB] = 1024L;
    m_[SIZE_MiB] = 1048576L;
    m_[SIZE_GiB] = 1073741824L;
    m_[SIZE_TiB] = 1099511627776L;
    m_[SIZE_PiB] = 1125899906842624L;
    m_[SIZE_KB] = 1000L;
    m_[SIZE_MB] = 1000000L;
    m_[SIZE_GB] = 1000000000L;
    m_[SIZE_TB] = 1000000000000L;
    m_[SIZE_PB] = 1000000000000000L;

    return m_[ut];
}

ZPSOE_SHARED_LIB_API byte_t to_byte(
        const unit_type_t ut, const uint_t u) {
    return to_byte(ut) * u;
}

ZPSOE_SHARED_LIB_API uint_t to_size(
        const unit_type_t ut, const byte_t b, const uint32_t precision) {
    const uint_t b_ = static_cast<uint_t>(b);

    if (ut == SIZE_Byte) return b_;

    uint_t size_ = b_ / to_byte(ut);

    if (precision == 0)
        // 向上取整
        size_ = ceil(size_);
    else
        // 四舍五入，并保留指定的有效数
        size_ = zdouble::round(size_, precision);

    return size_;
}

} /* namespace zunit */

} /* namespace zalgorithm */

} /* namespace zpsoe */
